package com.itzhigui.task;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

/**
 * 测试异步任务
 *
 * @author java1412
 * @since 2024-04-15 15:46:47
 */
@Component
public class MyTask2 {

    // 任务一执行，耗时4秒
    @Async // 表示当前的方法是一个异步方法
    public Future<String> task1() {
        long start = System.currentTimeMillis();
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        System.out.println("任务一耗时:" + (end - start) / 1000.0 + "秒");
        return new AsyncResult<String>("ok");
    }

    // 任务二执行，耗时2秒
    @Async // 表示当前的方法是一个异步方法
    public Future<String> task2() {
        long start = System.currentTimeMillis();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        System.out.println("任务二耗时:" + (end - start) / 1000.0 + "秒");
        return new AsyncResult<String>("ok");
    }

    // 任务三执行，耗时1秒
    @Async // 表示当前的方法是一个异步方法
    public Future<String> task3() {
        long start = System.currentTimeMillis();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        System.out.println("任务三耗时:" + (end - start) / 1000.0 + "秒");
        return new AsyncResult<String>("ok");
    }
}
